<template>
  <view class="page-container">
    <nav-bar title="商品详情" textAlign="center" @load="handleLoadNav"></nav-bar>
    <scroll-view scroll-y="true" :style="{'height':viewHeight+'px'}" v-if="commodityContent">
      <view style="width: 100%;">
        <view class="user-container">
          <view class="user-info">
            <!-- 头像 -->
            <view class="avatar" @click="handleJumpPage(commodityContent.userId)">
              <image :src="commodityContent.avatar" mode=""></image>
            </view>
            <!-- id和发布时间 -->
            <view class="info">
              <view>
                {{ commodityContent.userName }}
              </view>
              <view>
                {{commodityContent.createTime|formatDate("MM月dd日")}}发布
              </view>
            </view>
          </view>
          <!--          <view class="attention" v-if="userId !== commodityContent.userId">
            <view v-if="commodityContent.fansState" class="attention-active" @click="userFollow">
              已关注
            </view>
            <view v-else class="attention-default" @click="userFollow">
              +关注
            </view>
          </view> -->

          <block v-if="userId !== commodityContent.userId">
            <view v-if="commodityContent.fansState&&!commodityContent.followState" class="follow-on"
              @click="userFollow">已关注</view>
            <view v-else-if="commodityContent.fansState&&commodityContent.followState" class="follow-on"
              @click="userFollow">互相关注</view>
            <view v-else class="follow-off" @click="userFollow"> +关注 </view>
          </block>
        </view>

        <!-- 图片展示 -->
        <view class="image-container">
          <swiper circular="true" :indicator-dots="true" :autoplay="false" :interval="3000" :duration="500"
            indicator-active-color="#3FD3D1" indicator-color="#ffffff">
            <swiper-item v-for="(item, index) in commodityImage" :key="index" @click="handlePrevieimg(index)">
              <view class="image-item">
                <image :src="item" mode="aspectFill"></image>
              </view>
            </swiper-item>
          </swiper>
        </view>


        <!-- 附加信息 -->
        <view class="content-container">
          <view class="title">
            {{ commodityContent.goodsName }}
          </view>
          <view class="content">
            <text selectable>
              {{ commodityContent.goodsDescribe }}
            </text>
          </view>
          <view class="attr-container">
            <view class="classify">
              <view class="classify-item" v-for="item in commodityContent.tag" :key="item">
                {{ item }}
              </view>
            </view>
            <view class="price">
              ￥ {{ commodityContent.goodsPrice }}
            </view>
          </view>
        </view>
        <!-- 评论 -->
        <common-comments :creatorUserId="commodityContent.userId" :currentUserId="userId"
          :loadMainCommentData="handleGetMainCommentList" :loadChildCommentData="handleGetChildCommentList"
          :removeCommentData="handleRemoveCommentData" :sendCommentData="handleSendCommentData"
          :likeComment="handleLikeComment" :commentNum="commentNum" :props="commenProps">
        </common-comments>
      </view>
    </scroll-view>
    <view class="data-empty" v-if="emptyData">
      <view class="empty__image">
        <image src="/static/empty.png"></image>
      </view>
      <text class="empty__description">商品不存在</text>
    </view>
  </view>
</template>

<script>
  import {
    getGoodsContentApi,
    postUserFollowApi,

    getCommentsApi,
    deleteReplyApi,
    postSendOutApi,

    postreplyThumbsUpApi,
  } from "@/api/used/product-details.js";
  export default {
    data() {
      return {
        viewHeight: 0,
        goodsId: "",
        // 商品信息
        commodityContent: null,
        userId: "",
        commentNum: 0,
        // 配置
        commenProps: {
          content: 'content',
          avatar: "avatar",
          commentId: "commentId",
          commentsNum: "commentsNum",
          content: "content",
          createTime: "createTime",
          likeNum: 'likeNum',
          likeStatus: "status",
          userId: "userId",
          userName: "userName",
          wasRepliedName: 'wasRepliedName',
        },
        emptyData: false
      };
    },
    computed: {
      commodityImage() {
        return this.commodityContent && this.commodityContent.goodsId ? this.commodityContent.goodsImage.split(";") :
      [];
      }
    },
    onShow() {
      console.log('onshow');
      getApp().globalData.getUser()
      if (getApp().globalData.login) {
        this.userId = getApp().globalData.getUser().userId
        this.handleGetGoodsContent();
      } else {
        uni.switchTab({
          url: "/pages/my/my"
        })
      }
    },
    onLoad(e) {
      console.log('onLoad');
      this.goodsId = e.id;
      this.not2User = e.not2User;
      // 已登录获取文章数据 未登录返回我的页面

    },
    onShareAppMessage() {},
    onShareTimeline() {},
    methods: {
      handleLoadNav({
        height,
        navHeight
      }) {
        // 可移动视图的高度 = 视图高度 - 导航栏高度
        this.viewHeight = height - navHeight;
      },
      // 获取商品内容
      async handleGetGoodsContent() {
        uni.showLoading({
          mask: true
        })
        const {
          data: res
        } = await getGoodsContentApi(this.goodsId);
        if (res.success) {
          if (res.data.list.length > 0) {
            let data = res.data.list[0];
            this.$set(this, 'commodityContent', data);
          } else {
            this.emptyData = true;
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        } else {
          this.emptyData = true;
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
        // 内容

        // 图片
        uni.hideLoading()
      },
      // 跳转到用户界面
      handleJumpPage(uid) {
        if (this.not2User == 'true') {
          return;
        }
        uni.navigateTo({
          url: `/pages/my/userInfo/userInfo?id=${uid}`
        });
      },
      // 关注
      userFollow() {
        let uid = this.commodityContent.userId;
        var app = this;
        if (this.commodityContent.fansState == true) {
          uni.showModal({
            title: "提示",
            content: "是否取消关注",
            success: function(res) {
              if (res.confirm) {
                postUserFollowApi(uid).then(res => {
                  app.commodityContent.fansState = !app
                    .commodityContent.fansState;
                });
              } else if (res.cancel) {
                return;
              }
            },
          });
        } else {
          // uni.$http.post(`//ym_server/fans/addFollow?id=${uid}`)
          postUserFollowApi(uid).then(res => {
            this.commodityContent.fansState = !this.commodityContent
              .fansState;
          });
        }
      },
      // 预览图片
      handlePrevieimg(index) {
        uni.previewImage({
          urls: this.commodityImage,
          current: index,
          longPressActions: {
            itemList: ["发送给朋友", "保存图片", "收藏"],
            success: function(data) {},
            fail: function(err) {},
          },
        });
      },
      // ------------------------------------------------------ 评论
      // 加载主评论列表
      async handleGetMainCommentList(data) {
        const {
          data: res
        } = await getCommentsApi(this.goodsId, data.page)
        this.commentNum = res.data.list.total;
        return {
          pages: res.data.list.pages,
          data: res.data.list.records,
          success: res.success
        }
      },
      // 加载子评论列表
      async handleGetChildCommentList(data) {
        const {
          data: res
        } = await getCommentsApi(this.goodsId, data.page, data.ext.commentId)
        return {
          pages: res.data.list.pages,
          data: res.data.list.records,
          success: res.success
        }
      },
      // 删除评论
      async handleRemoveCommentData(data) {
        let {
          data: res
        } = await deleteReplyApi(data.commentId);
        res.success && this.commentNum--
        return {
          success: res.success
        }
      },
      // 发布评论
      async handleSendCommentData(data) {
        let type = data.type;
        let content = data.content;
        let args = [];
        if (type == 0) {
          // 默认评论参数
          args = [content, this.goodsId];
        } else {
          let commentId = data.data.commentId;
          // 回复评论参数
          args = [content, this.goodsId, commentId];
        }
        let {
          data: res
        } = await postSendOutApi(...args);
        res.success && this.commentNum++
        return {
          success: res.success,
          data: res.data.comment,
          message: res.message,
        }
      },
      // 点赞评论
      async handleLikeComment(data) {
        let commentId = data.commentId;
        let status = data.status;
        let likeNum = data.likeNum;
        let {
          data: res
        } = await postreplyThumbsUpApi(commentId);
        !status ? likeNum++ : likeNum--;
        return {
          success: res.success,
          status: !status,
          likeNum: likeNum
        }
      }

    },
  };
</script>

<style lang="scss" scoped>
  .page-container {
    background-color: #fff;
    // height: calc(100vh - var(--window-top));
    width: 100%;
    height: 100vh;
    overflow: hidden;

    scroll-view {
      width: 100%;
      height: 100%;
    }

  }

  .user-container {
    display: flex;
    padding: 20rpx 32rpx;
    align-items: center;
    justify-content: space-between;

    .user-info {
      display: flex;
      align-items: center;

      .avatar image {
        width: 88rpx;
        height: 88rpx;
        border-radius: 50%;
        margin-right: 12rpx;
        box-shadow: 0 0 4rpx 0 rgba(0, 0, 0, 0.1);
      }

      .info {
        margin-left: 8rpx;

        >view:nth-child(1) {
          font-size: 28rpx;
          font-weight: 500;
        }

        >view:nth-child(2) {
          font-size: 24rpx;
          color: #7a7a7a;
        }

      }

    }

    .follow-off {
      width: 124rpx;
      height: 52rpx;
      background-color: #3FD3D1;
      border-radius: 56rpx;
      font-size: 28rpx;
      color: #ffffff;
      text-align: center;
      line-height: 52rpx;
    }

    .follow-on {
      height: 52rpx;
      // background-colo: #C0C0C0;
      border-radius: 56rpx;
      font-size: 24rpx;
      // color: #FFFFFF;
      text-align: center;
      line-height: 52rpx;
      padding: 0 16rpx;
      border: 1px solid rgba(102, 102, 102, 0.4);
    }

    .attention {
      .attention-default {
        width: 124rpx;
        height: 52rpx;
        background-color: #3fd3d1;
        border-radius: 56rpx;
        font-size: 28rpx;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .attention-active {
        width: 124rpx;
        height: 52rpx;
        background-color: #c0c0c0;
        border-radius: 56rpx;
        font-size: 28rpx;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

  }

  .image-container {
    width: 100%;
    height: 800rpx;
    padding: 24rpx 32rpx;
    box-sizing: border-box;

    swiper {
      width: 100%;
      height: 100%;
    }

    .image-item {
      width: 100%;
      height: 100%;
      padding: 0 16rpx;
      box-sizing: border-box;

      image {
        border-radius: 16rpx;
        width: 100%;
        height: 100%;
      }
    }
  }


  .content-container {
    border-bottom: #eef2f4 solid 2rpx;
    width: 680rpx;
    margin: 24rpx 34rpx;

    .title {
      font-size: 32rpx;
      font-weight: 500;
      word-break: break-all;
      word-wrap: break-word;
    }

    .content {
      font-size: 28rpx;
      margin: 0 0 20rpx 0;
      word-break: break-all;
      word-wrap: break-word;
    }

    .attr-container {
      width: 100%;
      height: 70rpx;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .classify {
        display: flex;
        flex-wrap: wrap;

        .classify-item {
          height: 40rpx;
          box-sizing: border-box;
          padding: 0 16rpx;
          border-radius: 16rpx;
          border: solid #3fd3d1 2rpx;
          color: #3fd3d1;
          text-align: center;
          line-height: 34rpx;
          font-size: 20rpx;
          font-weight: 400;
          margin-right: 12rpx;
          margin-bottom: 12rpx;
        }
      }

      .price {
        color: #ff756a;
        font-size: 36rpx;
        flex-shrink: 0;
        line-height: 40rpx;
      }
    }
  }

  .data-empty {
    box-sizing: border-box;
    padding: 64px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .empty__image {
      width: 320rpx;
      height: 320rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .empty__description {
      padding: 0 120rpx;
      color: #969799;
      font-size: 28rpx;
      line-height: 40rpx;
    }

    .btn {
      margin-top: 32rpx;
      display: inline-block;
      color: #03a9f4;
    }
  }
</style>